require 'digest/sha1'

# this model expects a certain database layout and its based on the name/login pattern. 
class User < ActiveRecord::Base
  has_many :tasks
  has_many :notes
  has_and_belongs_to_many :projects
  
  def self.authenticate(login, pass)
    find(:first, :conditions=>["login=? AND password=?", login, sha1(pass)])
  end  
  
  def accept_invitation(inv_arr) # TODO: test multiple invitations
    inv_arr.each { |i|
      p = Project.find(i.project_id)
      projects << p if not projects.member?(p)
      i.destroy
    }
  end
  
  def decline_invitation(inv_arr) # TODO: test multiple invitations
    inv_arr.each { |i|
      i.destroy
    }
  end

  
  protected
  
  def self.sha1(pass)
    Digest::SHA1.hexdigest("laphrasedelamort#{pass}quitue")
  end
  
  before_create :crypt_password
  before_update :crypt_password_on_update
  
  def crypt_password
    #puts "Crypting"
    write_attribute("password", self.class.sha1(password))
  end
  
  validates_length_of :name, :within => 1..40
  validates_length_of :login, :within => 1..40
  validates_length_of :password, :within => 4..40
  validates_presence_of :login, :name
  validates_uniqueness_of :login, :case_sensitive => false
  validates_uniqueness_of :name, :case_sensitive => false # also the name as we assign users to projects by name
  validates_uniqueness_of :email, :case_sensitive => false, :if => Proc.new {|u| u.email and not u.email.empty?}
  validates_presence_of :password, :password_confirmation, :if => :validate_password_confirmation?
  validates_confirmation_of :password,:if => :validate_password_confirmation?
  
  def crypt_password_on_update
    crypt_password if validate_password_confirmation?
  end
  
  def validate_password_confirmation?
    #puts "p=#{password}, c=#{password_confirmation}"
     (password and password_confirmation)
  end  
  
end
